// packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails.js
let location = require("../../../mybehaviors/location/location");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [location],
  data: {
    locationStatus: false, //定位开关
    locationMore: false,
      activeNames: [],
      query: {
        longitude: "",
        latitude: "",
        id: "",
        basic_info:1
      },
      zIndex:100,
      lately: [], //飘窗滚动数据
      optionId: 0, //规格ID
      total: 1,
      favorite: false, //收藏开关
      goodsActive: 0,
      beginStatus: 1, //商品售卖状态
      aroundGoods: {},
      count: "",
      shopAddress: {},
      getGoods: {},
      now: "",
      productIndex: 0,
      detailsFlag:false,
      goodsOptionOpen: false,

      //客服插件
      showKefu: false,
      customer_open: "",
      cservice: "",
      service_mobile: "",
      service_QRcode: '',
      presentTime: "", //获取本地时间

      //处理的时间格式
      formatbeginTime: '',
      formatEndTime: '',
      formatPoints: '',
      validBeginDate:'',
      validEndDate: '',
      afterTime: '',
      beforeTime: '',
      computingFlase: false,
      plugin_setting:{},
      iPnoneBottomBol: false,
      description:'',
      goodsDesc:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.now = new Date(this.timestampToTime(new Date().valueOf() / 1000)).valueOf() / 1000;
    if(options.goodsId) {
      this.setData({
        'query.id': Number(options.goodsId),
        presentTime: new Date().getTime()
      })
    }
    this.getKefu();
    this.goodsdetails();
    this.getiPnoneBottom();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if(!this.data.query.latitude  && !this.data.query.latitude) {
      try {
        this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
          this.setData({
            'query.latitude': e.lat,
            'query.longitude': e.lng,
          });
          this.goodsdetails();
        });
      } catch (e) {
        this.goodsdetails();
        console.log(e);
      }
    }
    // let FormatbeginTime = this.timestampToTime(this.data.aroundGoods.beginTime);

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  tourView(){
    if(this.data.aroundGoods?.content.includes('https://cdn.lianlianlvyou.com')) {
      wx.navigateTo({
        url: '/packageF/tourAround/out/out?src='+ this.data.aroundGoods?.content,
      })
    }
  },
 
  goodsdetails() {
    if (this.data.query.latitude === "" && this.data.query.longitude === "") {
      this.setData({
        locationMore: false,
      })
    } else {
      this.setData({
        locationMore: true,
      })
    }
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: this.data.query,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let getGoods= res.data.get_goods;
          let plugin_setting = res.basic_info?.plugin_setting;
          let aroundGoods =  res.data.plugin?.travel_around.data?.travel_around_goods;
          if(aroundGoods?.content.includes('https://cdn.lianlianlvyou.com')) {
            this.setData({
              detailsFlag:true
            })
          } else {
            this.setData({
              detailsFlag:false
            })
          }
          let description = aroundGoods.content?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
          let goodsDesc =getGoods .content?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'); 
          this.setData({
            shopAddress: res.data.plugin?.travel_around.data?.shop_address,
            aroundGoods: aroundGoods,
            favorite: res.data.is_favorite ? (res.data.is_favorite.status == 1 ? true : false) : false,
            count: res.data.plugin?.travel_around.data?.count,
            getGoods: getGoods,
            lately: res.data.plugin?.travel_around.data?.lately,
            optionId: getGoods?.has_many_options[0].id,
            plugin_setting:plugin_setting,
            formatbeginTime: this.timestampToTime(aroundGoods.beginTime),
            formatEndTime: this.timestampToTime(aroundGoods.endTime),
            formatPoints: this.points(aroundGoods.endTime),
            validBeginDate: this.timestampToTime(aroundGoods.validBeginDate),
            validEndDate: this.timestampToTime(aroundGoods.validEndDate),
            afterTime: this.afterTimeData(aroundGoods.beginTime),
            computingFlag: this.computingTime(this.data.presentTime, aroundGoods.endTime),
            beforeTime: this.beforeDay(aroundGoods.endTime),
            description:description,
            goodsDesc:goodsDesc
          })
          let nowtime = new Date().getTime();
          if (this.data.aroundGoods.beginTime > nowtime) {
            //活动是否开售
            this.setData({
              beginStatus: 0
            })
          }
          if (this.data.plugin_setting?.travel_around?.is_ios_sell === 1 || this.data.plugin_setting?.travel_around?.is_ios_sell === "1") {
            // 卡券商品 并开启 IOS禁用
            if (app.isIosOrAndroid() === "ios") {
              this.setData({
                beginStatus: -1
              })
            }
          }
          this.goodsOption();
        } else {
          wx.showModal({
            content: res.msg,
            success (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goodsOption() {
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.option");
    let json = {
      goods_id: this.data.query.id
    };
    app._postNetWork({
      url: urlStr,
      data: json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            categoriesGoodsList: res.data,
          })
          this.getArrEqual(res.data, this.data?.getGoods?.has_many_options);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getArrEqual(arr1, arr2) {
    //周边游供应链的商品，plugin.jd-supply.frontend.goods.option接口返回为1的才去取库存，返回为0的就库存直接是0
    if (arr1 === null) {
      this.setData({
        beginStatus: -1
      })
      return;
    }
    let getGoods = this.data.getGoods;
    for (let i = 0; i < arr2.length; i++) {
      if (arr1[arr2[i].id] == 0) {
        getGoods.has_many_options[i].stock = 0;
      }
    }
    this.setData({
      getGoods:getGoods
    })
  },
  timestampToTime(timestamp) {
    if (!timestamp || timestamp == 0) return;
    
    var date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + "/";
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "/";
    let D = this.change(date.getDate()) + " ";
    let h = this.change(date.getHours()) + ":";
    let m = this.change(date.getMinutes());

    // let s = this.change(date.getSeconds());
    return Y + M + D + h + m;
  },
  points(backTime) {
    let TimeDate = new Date(Number(backTime));
    let disposeTime = new Date(new Date(TimeDate).toLocaleDateString()).getTime();
    var date1 = new Date(new Date().toLocaleDateString()).getTime();
    return date1 === Number(disposeTime) ? true : false;
  },
  computingTime(afterTime, backTime) {
    if (!Number(backTime)) return;
    let res = Number(afterTime) - Number(backTime);
    if (res === 0 || res > 0) {
      this.setData({
        beginStatus: 2
      })
      return true;
    } else {
      return false;
    }
  },
  beforeDay(time) {
    if (!Number(time)) return;
    return time - Number(this.data.presentTime);
  },
  beforeDayTime(time) {
    if (!Number(time)) return;
    let timeBefore = new Date(Number(time));
    timeBefore = +timeBefore - 1000 * 60 * 60 * 24;
    timeBefore = new Date(Number(timeBefore));
    return Number(timeBefore);
  },
  afterTimeData(time) {
    if (!Number(time)) return;
    return time - Number(this.data.presentTime);
  },
  navigation(event) {
    let {latitude, longitude, shopaddress} = event.currentTarget.dataset;
    console.log(latitude,longitude,shopaddress);
    let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
      wx.openLocation({
        latitude: point.lat,
        longitude: point.lng,
        name: shopaddress,
        scale: 18
      });
  },
  callStore(event) {
    let phone = event.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone
    });
  },
  tapIndex() {
    //首页跳转
    wx.navigateTo({
      url: '/packageF/tourAround/travelIndex/travelIndex'
    });;
  },
  storeNav() {
    wx.navigateTo({
      url: `/packageF/tourAround/tourAroundStoreList/tourAroundStoreList?goodsId=${this.data.query.id}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}`
    });;
  },
  clickChat() {
    this.setData({
      showKefu: true
    })
  },
  getiPnoneBottom() {
    try {
      var value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        this.setData({
          iPnoneBottomBol: true,
        });
      }
    } catch (e) {}
  },
  // 获取客服
  getKefu() {
    let goods_id = this.data.query?.id;
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_id: goods_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customer_open:res.data.customer_open == 0?false:true,
            showKefu: false,
            cservice: res.data.cservice,
            service_QRcode: res.data.service_QRcode,
            service_mobile: res.data.service_mobile,
          });
          console.log(this.data.cservice);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  onFavorite() {
    let urlStr = '';
    let favorite = !this.data.favorite;
    if(favorite) {
      urlStr = app.getNetAddresss("member.member-favorite.store");
    } else {
      urlStr = app.getNetAddresss("member.member-favorite.destroy");
    }
    urlStr += "&goods_id=" + this.data.query.id;
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        this.setData({
          favorite: favorite,
        });
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 3000,
        });
      },
      fail: function (res) {},
    });
  },
  specificationOn(event) {
    let {index,id} = event.currentTarget.dataset;
    this.setData({
      productIndex: index,
      optionId: id
    })
  },
  onPreorder() {
    if (this.data.aroundGoods.ecommerce === 0) {
      let url = "/packageD/buy/myOrder_v2/myOrder_v2?tag=tourAround";
      let _urlParam = `&goodsId=${this.data.query.id}&optionsId=${this.data.optionId}&total=${this.data.total}&orderShowDate=${this.data.aroundGoods.orderShowDate}`;
      wx.navigateTo({
        url: url + _urlParam
      });
    }
  },
  goodsLikeOn(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id,
    })
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.getGoods?.title,
      imageUrl:this.data.getGoods?.thumb,
      path: `packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails?goodsId=${this.data.query?.id}&latitude=${this.data.query?.latitude}&longitude=${this.data.query?.longitude}`
    };
  },
  onShareTimeline() {
    return {
      title: this.data.getGoods?.title,
      imageUrl:this.data.getGoods?.thumb,
      path: `packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails?goodsId=${this.data.query?.id}&latitude=${this.data.query?.latitude}&longitude=${this.data.query?.longitude}`
    };
  }
})